//
//  CSHomeSearchSaleController.m
//  CarSalesMS_GCX
//
//  Created by Ssky on 2016/11/18.
//  Copyright © 2016年 Tony. All rights reserved.
//

#import "CSHomeSearchSaleController.h"
#import "CSSearchSaleCell.h"
//#import "CSHomeSearchDashedModifyController.h"
#import "CSGXHomeSaleCommitPreviewController.h"

#import "TSaleInfoDAL.h"
#import "TOrderInfoDAL.h"

#import "TSaleInfoModel.h"


NSString * const searchSaleCellId = @"searchSaleCellId";
NSString * const searchSaleHeaderId = @"searchSaleHeaderId";

@interface CSHomeSearchSaleController () <UITableViewDataSource, UITableViewDelegate>

/// 数据源 --based orderNo
@property (nonatomic, strong) NSArray<TSaleInfoModel *> * saleListDetail;

@property(nonatomic,weak) UITableView * tvSaleComm;

@property (nonatomic,weak) UIView * vFooter;

///saleModificationList
@property (nonatomic, strong) NSArray<TSaleInfoModel *> * saleModificationList;

@end

@implementation CSHomeSearchSaleController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initData];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - actions

- (void)leftItemClick:(id)sender {
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)btnDashedBackClick:(id)sender {
    
    UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:@"确认红冲" message:@"红冲/红冲改单" preferredStyle:UIAlertControllerStyleAlert];
    
    if (self.orderDashedModel.orState == 3) {
        alertVc.message = @"此订单已是红冲单，不能再次红冲！";
        UIAlertAction * actionDone = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //
            
        }];
        [alertVc addAction:actionDone];
        [self presentViewController:alertVc animated:YES completion:nil];
        
        NSLog(@"此订单已是红冲单，不能再次红冲！");
        return;
    }
    
    UIAlertAction * actionDashed = [UIAlertAction actionWithTitle:@"红冲" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        // dashed back
        [self dashedBack];
        
        [CSGXProgressTool showSuccessWithStatus:@"红冲成功！" delay:0.5];
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    
    UIAlertAction * actionModify = [UIAlertAction actionWithTitle:@"红冲改单" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // dashed modify
//        self.saleModificationList = self.saleListDetail.mutableCopy;
        self.saleModificationList = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self.saleListDetail]];
//          -- 0x0000600000159de0
        [self dashedBackModify];
        
    }];
    
    [alertVc addAction:actionDashed];
    [alertVc addAction:actionModify];
    [self presentViewController:alertVc animated:YES completion:nil];
}




#pragma mark - methods
- (void)initData {
    self.saleListDetail = [NSArray<TSaleInfoModel *> array];
}

- (void)loadData {
    [self loadDataWithOrderNo:self.orderNoSale];
}

- (void)loadDataWithOrderNo:(NSString *)orderNo {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.saleListDetail = [TSaleInfoDAL loadListWithOrderNo:orderNo];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tvSaleComm reloadData];
        });
    });
}

- (NSString *)getNegativeStringWithOriginStr:(NSString *)origin {
    NSString * result = @"";
    
    NSArray * arr = [origin componentsSeparatedByString:@","];
    for (NSString * str in arr) {
        result = [result stringByAppendingFormat:@"-%@,", str];
    }
    return [result subStringFrontOfLastIndex:1];
}

- (void)dashedBack {
    // dashed back
    for (TSaleInfoModel * model in self.saleListDetail) {
        model.sCount = [self getNegativeStringWithOriginStr:model.sCount];
        model.sUnitMoney = [self getNegativeStringWithOriginStr:model.sUnitMoney];
        model.sTotalMoney = -1.0 * model.sTotalMoney;
        model.sSaleType = 5; //5-红冲 DashedBack
        
        //update tSaleInfo based sId.
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [TSaleInfoDAL updateSaleModel:model];
        });
    }
    
    //orderDashedModel
    self.orderDashedModel.orTotalMoney = -1 * self.orderDashedModel.orTotalMoney;
    self.orderDashedModel.orState = 3; //dashed back 红冲
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [TOrderInfoDAL updateOrderModel:self.orderDashedModel];
    });
}

- (void)dashedBackModify {
    [self dashedBack];
    
    CSGXHomeSaleCommitPreviewController * previewDashedModifyVc = [[CSGXHomeSaleCommitPreviewController alloc] init];
    previewDashedModifyVc.dataPreviewDict = @{@"orderModel":[[TOrderInfoModel alloc] init], @"saleList":self.saleModificationList};
    [self.navigationController pushViewController:previewDashedModifyVc animated:YES];
}


#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.saleListDetail.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CSSearchSaleCell * cell = [tableView dequeueReusableCellWithIdentifier:searchSaleCellId forIndexPath:indexPath];
    cell.dataDictSaleCell = @{@"index":@(indexPath.row), @"saleModelDetail":self.saleListDetail[indexPath.row]};
    return cell;
}



#pragma markl - setupUI
- (void)setNavBar {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"后退" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick:)];
}

-(void) setupUI {
    //
    [self setNavBar];
    
    UITableView * tvSaleComm = [[UITableView alloc] init];
    [self.view addSubview:tvSaleComm];
    
    [tvSaleComm registerClass:[CSSearchSaleCell class] forCellReuseIdentifier:searchSaleCellId];
    
//    tvSaleComm.bounces = NO;
//    tvSaleComm.backgroundColor = [UIColor redColor];
    
    tvSaleComm.dataSource = self;
    tvSaleComm.delegate = self;
    
    tvSaleComm.rowHeight = 50;
//    tvSaleComm.estimatedRowHeight = 60;
//    tvSaleComm.rowHeight = UITableViewAutomaticDimension;
    
    [tvSaleComm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.view);
    }];
    
    // vFooter
    UIView * vFooter = [[UIView alloc] init];
    [self.view addSubview:vFooter];
    
    vFooter.backgroundColor = kColorBar;
    
    [vFooter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tvSaleComm.mas_bottom);
        make.leading.bottom.trailing.equalTo(self.view);
        make.height.offset(50);
    }];
    
    // btnDashedBack 红冲
    UIButton * btnDashedBack = [UIButton gx_textButton:@"红冲" fontSize:18 normalColor:nil selectedColor:nil];
    [self.view addSubview:btnDashedBack];
    
    [btnDashedBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.trailing.equalTo(vFooter);
        make.width.offset(60);
    }];
    
    [btnDashedBack addTarget:self action:@selector(btnDashedBackClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //
    self.tvSaleComm = tvSaleComm;
}

#pragma mark - setter & getter

- (void)setOrderDashedModel:(TOrderInfoModel *)orderDashedModel {
    _orderDashedModel = orderDashedModel;
    
    _orderNoSale = orderDashedModel.orOrderNo;
}











@end
